﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Activation;
using RrslLite.Net.Contracts;
using RrslLite.Net.Ioc;
using RrslLite.Net.Messages;

namespace RrslLite.Host
{
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class WcfMessageService : IWcfMessageService
    {
        public virtual Message[] InvokeOperations(params Message[] messages)
        {
            var result = new List<Message>();

            foreach (var wcfMessage in messages)
            {
                result.Add(InvokeOperation(wcfMessage));
            }

            return result.ToArray();
        }

        protected virtual Message InvokeOperation(Message message)
        {
            var result = message;

            try
            {
                var objectFromFactory = IocHelper.ContainerInstance.Resolve<IRegisterable>(message.OperationContainerName);
                Type objectType = objectFromFactory.GetType();
                var method = objectType.GetMethod(message.OperationName);
                var parameters = method.GetParameters();
                var filledParameters = new List<object>();

                if (message.OperationParameters != null)
                {
                    filledParameters.AddRange(parameters.Select(methodParameter => message.OperationParameters[methodParameter.Name]));
                }

                result.Result = method.Invoke(objectFromFactory, filledParameters.ToArray());
            }

            catch (Exception e)
            {
                result.ContainsException = true;
                result.Result = e.InnerException.Message;
            }

            return result;
        }

    }


}
